package com.iyue.portal.helper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.iyue.framework.BaseAction;
import com.iyue.sso.bean.SSOInfo;
import com.iyue.sso.helper.SSOUtil;
import com.iyue.user.helper.UserFunctions;
import com.iyue.user.pojo.UserBasic;
import com.iyue.util.IpSafe;
import com.iyue.util.Logit;

/**
 * 《网站》控制器
 * 
 * @author 孙晓晔
 * @version $Id: PortalController.java,v 1.3 2011/01/07 10:16:14 fresh Exp $
 */
public abstract class PortalController extends BaseAction {
	@Override
	public ActionForward display(HttpServletRequest request,
			HttpServletResponse response, String view) throws Exception {
		String msg = request.getParameter("msg");
		if (msg != null && msg.length() > 0) {
			request.setAttribute("msg", msg);
		}

		return super.display(request, response, view);
	}

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return super.execute(mapping, form, request, response);
	}

	/**
	 * 访问日志
	 * 
	 * @see com.iyue.framework.BaseAction#accesslog(javax.servlet.http.HttpServletRequest,
	 *      long)
	 */
	protected void accesslog(HttpServletRequest request, long totaltime) {
		// if (request.getMethod().equalsIgnoreCase("get")) {
		// visitlog(request);
		// }

		userAccessLog(request, totaltime);
	}

	protected void userAccessLog(HttpServletRequest request, long totaltime) {
		if (request == null) {
			return;
		}

		String action2 = (String) request.getAttribute("do");
		if (action2 == null) {
			action2 = "";
		}

		String tpl = (String) request.getAttribute("tpl");
		if (tpl == null) {
			tpl = "html";
		}

		String src = src(request);
		if (src == null) {
			src = "";
		}

		String mobile = null;
		if (mobile == null) {
			// SSOInfo sso = (SSOInfo) request.getAttribute("SSO");
			// if (sso != null) {
			// mobile = sso.getMobile().toString();
			// } else {
			mobile = "";
			// }
		}

		String username = username(request);
		if (username == null) {
			username = "";
		}

		String uri = request.getRequestURI();
		if (uri == null) {
			uri = "";
		}

		String ip = IpSafe.getIp(request);
		if (ip == null) {
			ip = "";
		}

		String ua = null;
		if (ua == null) {
			ua = "";
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		StringBuffer l = new StringBuffer();
		l.append(sdf.format(new Date()));
		l.append("|");
		l.append(uri);
		l.append("|");
		l.append(action2);
		l.append("|");
		l.append(tpl);
		l.append("|");
		l.append(src);
		l.append("|");
		l.append(mobile);
		l.append("|");
		l.append(username);
		l.append("|");
		l.append(ip);
		l.append("|");
		l.append(ua);
		l.append("|");
		l.append(String.valueOf(totaltime));
		l.append("|");
		l.append(request.getServerName());
		l.append(request.getRequestURI().toString());
		l.append("|");
		l.append(request.getQueryString());

		Logit.userAccessLog(l.toString());
	}

	/**
	 * 用户帐号
	 * 
	 * @param request
	 * @return
	 */
	protected String username(HttpServletRequest request) {
		SSOInfo info = SSOUtil.getSSO(request);
		if (info == null) {
			return null;
		}

		Integer uid = info.getUsername();
		if (uid == null) {
			return null;
		}

		return uid.toString();
	}

	/**
	 * 访客记录
	 * 
	 * @param request
	 *            请求
	 */
	protected abstract void visitlog(HttpServletRequest request);

	/**
	 * 通过会话获取用户
	 * 
	 * @param request
	 * @return
	 */
	public UserBasic user(HttpServletRequest request) {
		Integer username = (Integer) request.getAttribute("userId");
		if (username == null) {
			return null;
		}

		UserBasic user = UserFunctions.user(username.toString());
		if (user == null) {
			return null;
		}

		return user;
	}

	/**
	 * 
	 * @see com.iyue.framework.BaseAction#pretreat(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected void pretreat(HttpServletRequest request) {

		processGo(request); // 处理返回地址
		processRoot(request); // 处理根目录
		processParam(request); // 处理参数

		super.pretreat(request);
	}

	/**
	 * 处理返回地址
	 * 
	 * @param request
	 */
	private void processGo(HttpServletRequest request) {
		String go = request.getRequestURI();
		if (request.getQueryString() != null) {
			go += "?" + request.getQueryString();
		} else {
			go += "?do=" + (String) request.getAttribute("do");
		}

		try {
			go = URLEncoder.encode(go, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Pattern p = Pattern
				.compile("([\\W|\\w]*)(do%3D[\\W|\\w]*)(Post)([\\W|\\w]*)");
		Matcher matcher = p.matcher(go);
		if (matcher.find()) {
			go = matcher.group(1) + matcher.group(2) + matcher.group(4);
		}

		request.setAttribute("go", go);
	}

	/**
	 * 处理根路径
	 * 
	 * @param request
	 */
	private void processRoot(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer();
		sb.append(request.getScheme());
		sb.append("://");
		sb.append(request.getServerName());
		if (request.getServerPort() != 80) {
			sb.append(":");
			sb.append(request.getServerPort());
		}
		sb.append(request.getContextPath());
		sb.append("/");
		request.setAttribute("root", sb.toString());
		request.setAttribute("basehost", "/");

		request.setAttribute("url", request.getRequestURL().toString());
		request.setAttribute("uri", request.getRequestURI());
	}

	/**
	 * 处理状态保持参数
	 * 
	 * @param request
	 */
	private static void processParam(HttpServletRequest request) {
		String src = request.getParameter("src");
		if (src == null) {
			src = "10201";
		}
		StringBuffer p1 = new StringBuffer();
		p1.append("?src=");
		p1.append(src);

		request.setAttribute("p1", p1.toString());

	}
}
